package org.example.aigc.service.impl;

import org.example.aigc.service.UploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Objects;
import java.util.UUID;

@Service
public class UploadServiceImpl implements UploadService {

    public String uploadFile(MultipartFile file, String uploadPath) {
        try {
            String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
            String filePath = uploadPath + File.separator + fileName;
            // 将文件保存到服务器
            file.transferTo(new File(filePath));
            // 返回文件名
            return fileName;
        } catch (IOException e) {
            e.fillInStackTrace();
            return null;
        }
    }

    public int uploadChunk(MultipartFile chunk, int index, int chunkTotal, long fileSize, String fileName, long chunkSize, String uploadDirectory) {
        String[] splits = fileName.split("\\.");
        String type = splits[splits.length - 1];
        String resultFilePath = uploadDirectory + File.separator + fileName;

        int code = saveChunk(chunk, index, chunkSize, resultFilePath);
        if (code == 1) {
            // 保存分片失败
            return code;
        }
        if (Objects.equals(index, chunkTotal)) {
            return 0;
        } else {
            // 上传中
            return 2;
        }
    }

    private int saveChunk(MultipartFile chunk, int index, long chunkSize, String resultFileName) {

        try (RandomAccessFile randomAccessFile = new RandomAccessFile(resultFileName, "rw")) {
            // 偏移量
            long offset = chunkSize * (index - 1);
            // 定位到该分片的偏移量
            randomAccessFile.seek(offset);
            // 写入
            randomAccessFile.write(chunk.getBytes());
            // 保存分片正常
            return 0;
        } catch (IOException e) {
            e.fillInStackTrace();
            // 保存分片失败
            return 1;
        }
    }

    public int deleteFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return 1;
        }
        boolean flag = file.delete();
        return flag ? 0 : 2;
    }
}
